package com.lloydfinch.multirecyclerview

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

/**
 * Name: Adapter
 * Author: lloydfinch
 * Function: Adapter
 * Date: 2021/9/1 10:35 上午
 * Modify: lloydfinch 2021/9/1 10:35 上午
 */
class Adapter(private val datas: List<BaseItemBean>) : RecyclerView.Adapter<Adapter.BaseVH>() {

    private val TAG = "Adapter"

    /**
     * 点击item的事件
     */
    var onItemDeleteClick: ((position: Int) -> Unit)? = null

    /**
     * ViewHolder的工厂
     */
    private val vhs = SparseArray<VHFactory>()

    /**
     * 用来倒计时
     */
    private val timerHandler = Handler(Looper.getMainLooper())

    /**
     * 初始化工厂
     */
    init {
        vhs.put(ItemType.ITEM_BASE, BaseVHFactory())
        vhs.put(ItemType.ITEM_ON_SALE, OnSaleVHFactory())
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseVH = vhs.get(viewType).createVH(parent.context, parent)

    override fun onBindViewHolder(holder: BaseVH, position: Int) = holder.display(datas[position])

    override fun getItemCount(): Int = datas.size

    override fun onViewRecycled(holder: BaseVH) = holder.onRecycled()

    /**
     * 根据数据类型返回ViewType
     * @param position Int
     * @return Int
     */
    override fun getItemViewType(position: Int): Int = datas[position].type

    /**
     * ViewHolder工厂
     */
    abstract class VHFactory {
        abstract fun createVH(context: Context, parent: ViewGroup): BaseVH
    }

    /**
     * BaseViewHolder工厂
     */
    inner class BaseVHFactory : VHFactory() {
        override fun createVH(context: Context, parent: ViewGroup): BaseVH {
            return BaseVH(LayoutInflater.from(context).inflate(R.layout.item_base, parent, false))
        }
    }

    /**
     * OnSaleVH工厂
     */
    inner class OnSaleVHFactory : VHFactory() {
        override fun createVH(context: Context, parent: ViewGroup): BaseVH {
            return OnSaleVH(LayoutInflater.from(context).inflate(R.layout.item_on_sale, parent, false))
        }
    }

    /**
     * BaseViewHolder，
     */
    open inner class BaseVH(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private val tvTimer = itemView.findViewById<TextView>(R.id.tv_time)
        private val btnDelete = itemView.findViewById<TextView>(R.id.btn_delete)

        init {
            btnDelete.setOnClickListener {
                onItemDeleteClick?.invoke(adapterPosition)
            }
        }

        /**
         * 剩余倒计时
         */
        private var delay = 0L

        private val timerRunnable = Runnable {
            Log.d(TAG, "run: ${hashCode()}")
            delay -= 1000
            updateTimerState()
        }

        private fun startTimer() {
            timerHandler.postDelayed(timerRunnable, 1000)
        }

        private fun endTimer() {
            timerHandler.removeCallbacks(timerRunnable)
        }

        @SuppressLint("SetTextI18n")
        private fun updateTimerState() {
            if (delay <= 0) {
                // 倒计时结束了
                tvTimer.text = "已结束"
                itemView.setBackgroundColor(Color.GRAY)
                endTimer()
            } else {
                // 继续倒计时
                tvTimer.text = "${delay / 1000}S"
                itemView.setBackgroundColor(Color.parseColor("#FFBB86FC"))
                startTimer()
            }
        }

        /**
         * 展示时: 填充数据
         * @param bean BaseItemBean
         */
        open fun display(bean: BaseItemBean) {
            Log.d(TAG, "display: $adapterPosition")

            // 使用 终止时间 - 当前时间，计算倒计时还有多少秒
            delay = bean.terminalTime - System.currentTimeMillis()

            // 检测并更新timer状态
            updateTimerState()
        }

        /**
         * 被回收时: 移除倒计时
         */
        fun onRecycled() {
            Log.d(TAG, "onRecycled: $adapterPosition")

            // 终止计时
            endTimer()
        }
    }

    inner class OnSaleVH(itemView: View) : BaseVH(itemView) {
        private val tvName = itemView.findViewById<TextView>(R.id.tv_name)

        @SuppressLint("SetTextI18n")
        override fun display(bean: BaseItemBean) {
            super.display(bean)
            tvName.text = "${bean.id} 在售"
        }
    }
}